package edu.cug.water.crawler.job.task.committee;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import edu.cug.water.crawler.common.constant.Constant;
import edu.cug.water.crawler.common.constant.EsConstants;
import edu.cug.water.crawler.common.exception.RRException;
import edu.cug.water.crawler.common.utils.DateUtils;
import edu.cug.water.crawler.common.utils.EsUtils;
import edu.cug.water.crawler.job.entity.committee.SongLiaoWater;
import edu.cug.water.crawler.job.task.ITask;
import edu.cug.water.crawler.job.utils.AbstractCrawlerTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component("job:SongLiaoWater")
public class SongLiaoWaterTask extends AbstractCrawlerTask<SongLiaoWater> implements ITask {


    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private static final String REGEX =  "<font style=\"font-size:12px\">(.*)</font>";
    private static final String REGEX_FLOW = "<SCRIPT>cvt\\('(.*)'\\);</SCRIPT>";
    static final Pattern pattern = Pattern.compile(REGEX);
    static final Pattern patternFlow = Pattern.compile(REGEX_FLOW);

    @Autowired
    private EsUtils esUtils;

    @Override
    public int run(String params) throws IOException {
        init();

        ResponseEntity<String> response = getRequestBody();

        List<SongLiaoWater> results= getDataFromStr(response.getBody());
        log.info("{} converts results：{}", getClass().getName(), results.size());

        String s = esUtils.addDocuments(EsConstants.TypeConstant.SONG_LIAO_WATER.getValue(), results);
        Boolean aBoolean = esUtils.statusJudge(s);
        if (!aBoolean) {
            throw new RRException(getClass().getName() + Constant.LogConstants.THE_PROCESS_OF_ES_STORE_FAILED.getValue());
        }
        return results.size();
    }

    @Override
    protected void init() {
        super.init();
        url = "http://www.slwr.gov.cn/gwSqlServer/slwoadata/list";
        headers.set("Host", "www.slwr.gov.cn");
        headers.set("Connection", "keep-alive");
        headers.set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
        headers.set("Referer", "http://www.slwr.gov.cn/");
        headers.set("Accept-Encoding", "gzip, deflate");
        headers.set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
    }

    @Override
    public ResponseEntity<String> getRequestBody() {
        // 新版接口已不需要对编码进行转换
        // StringHttpMessageConverter m = new StringHttpMessageConverter(Charset.forName("GBK"));
        // .additionalMessageConverters(m).build();
        RestTemplate restTemplate = new RestTemplateBuilder().build();

        HttpEntity<Object> entity = new HttpEntity<>(null, headers);

        return restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
    }

    @Override
    public List<SongLiaoWater> getDataFromStr(String body) {
        if (StringUtils.isEmpty(body)) {
            throw new RRException(getClass().getName() + Constant.LogConstants.RESPONSE_IS_NULL.getValue());
        }

        List<SongLiaoWater> songLiaoWaters = JSON.parseArray(body, SongLiaoWater.class);

        LocalDateTime localDateTime = LocalDateTime.now();
        String dateString = localDateTime.format(formatter);

        for (SongLiaoWater songLiaoWater : songLiaoWaters) {
            songLiaoWater.setCreateTime(dateString);
        }
        return songLiaoWaters;
    }

    private String dealFluctuation(String s) {
        if(s.contains("down")) {
            return "down";
        } else if (s.contains("equal")) {
            return "equal";
        } else if (s.contains("up")) {
            return "up";
        }
        return "";
    }

    private String dealWaterStage(String s){
        Matcher matcher = patternFlow.matcher(s);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return s;
    }

}
